#include "crashcollect.h"
#include "signal.h"
#include <execinfo.h>
#include "QDir"
#include "QDateTime"
#include "qdebug.h"

CrashCollect::CrashCollect()
{

}

void signalHandler(int signum)
{
    QDateTime currentTime = QDateTime::currentDateTime();
    QString formattime = currentTime.toString("yyyy-MM-dd-HH-mm-ss");

    QString path = "./log/crash";
    QDir dir;
    if (!dir.mkpath(path)) {
        qDebug() << "creat path fail：" << path;
    }

    void* callstack[128];
    int frames = backtrace(callstack, 128);
    QString logPath = "./log/crash/" + formattime + ".log";
    FILE* f = fopen(logPath.toLocal8Bit(), "w");
    if (f) {
        backtrace_symbols_fd(callstack, frames, fileno(f));
        fclose(f);
    }

    // 终止程序
    exit(signum);
}

void CrashCollect::Register()
{
    signal(SIGSEGV, signalHandler);     //段错误
    signal(SIGABRT, signalHandler);     //异常终止
    signal(SIGFPE, signalHandler);      //浮点异常
    signal(SIGILL, signalHandler);     //非法指令
    signal(SIGBUS, signalHandler);      //总线错误
//    signal(SIGPIPE, signalHandler);     //管道破裂
    signal(SIGSYS, signalHandler);      //非法系统调用
}
